package utils

import (
	"math/rand"
	"time"
)

const (
	RandKindNum   = 1 << 0 // 纯数字
	RandKindLower = 1 << 1 // 小写字母
	RandKindUpper = 1 << 2 // 大写字母
	RandKindAll   = RandKindNum | RandKindLower | RandKindUpper
)

var randSource = rand.New(rand.NewSource(int64(time.Now().Nanosecond())))
var RandSelectSliceMap = map[int][]int{
	1: {1, 2, 3, 4, 5, 6, 7, 8, 9},                                                                //排除了0
	2: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25}, //排除了o
	3: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25}, //排除了O
}

// 随机字符串
func RandStringK(size int, kind int, isExclude0oO bool) []byte {
	scope := make([][]int, 0, 3)
	//if kind&RandKindNum != 0 {
	//	scope = append(scope, []int{10, 48})
	//}
	//if kind&RandKindLower != 0 {
	//	scope = append(scope, []int{26, 97})
	//}
	//if kind&RandKindUpper != 0 {
	//	scope = append(scope, []int{26, 65})
	//}

	if kind&RandKindNum != 0 {
		scope = append(scope, []int{9, 48, 1})
	}
	if kind&RandKindLower != 0 {
		scope = append(scope, []int{25, 97, 2})
	}
	if kind&RandKindUpper != 0 {
		scope = append(scope, []int{25, 65, 3})
	}

	result := make([]byte, size)
	l := len(scope)
	for i := 0; i < size; i++ {
		index := randSource.Intn(l)
		s, base, mapKey := scope[index][0], scope[index][1], scope[index][2]
		if isExclude0oO {
			result[i] = uint8(base + RandSelectSliceMap[mapKey][randSource.Intn(s)])
		} else {
			result[i] = uint8(base + randSource.Intn(s))
		}
	}
	return result
}

func RandString(len int, isExclude0oO bool) string {
	return string(RandStringK(len, RandKindAll, isExclude0oO))
}

func BuildNonce() string {
	return RandString(8, true)
}
